<template>
  <div class="notification-detail">
    <div class="page-header">
      <el-button 
        type="primary" 
        :icon="ArrowLeft" 
        @click="goBack"
        class="back-button"
      >
        返回通知列表
      </el-button>
      <h1>通知详情</h1>
    </div>

    <div class="content-wrapper">
      <el-card v-if="notification" class="notification-card">
        <!-- 通知标题和状态 -->
        <div class="notification-header">
          <div class="title-section">
            <h2 class="notification-title">{{ notification.title }}</h2>
            <el-tag 
              :type="notification.status === 'READ' ? 'success' : 'warning'"
              class="status-tag"
            >
              {{ notification.status === 'READ' ? '已读' : '未读' }}
            </el-tag>
          </div>
          <div class="type-section">
            <el-tag :type="getTypeTagType(notification.type)" class="type-tag">
              {{ getTypeText(notification.type) }}
            </el-tag>
          </div>
        </div>

        <!-- 通知内容 -->
        <div class="notification-content">
          <h3>详细内容</h3>
          <div class="content-text" v-html="formatContent(notification.content)"></div>
        </div>

        <!-- 通知元信息 -->
        <div class="notification-meta">
          <div class="meta-item">
            <span class="meta-label">创建时间：</span>
            <span class="meta-value">{{ formatDateTime(notification.createdAt) }}</span>
          </div>
          <div class="meta-item" v-if="notification.readAt">
            <span class="meta-label">阅读时间：</span>
            <span class="meta-value">{{ formatDateTime(notification.readAt) }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">通知ID：</span>
            <span class="meta-value">{{ notification.id }}</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button 
            v-if="notification.status === 'UNREAD'"
            type="primary" 
            @click="markAsRead"
            :loading="markingAsRead"
          >
            标记为已读
          </el-button>
          
          <el-button 
            type="info" 
            @click="goToRelatedPage"
            v-if="hasRelatedPage(notification.type)"
          >
            {{ getRelatedPageText(notification.type) }}
          </el-button>
          
          <el-button 
            type="danger" 
            @click="deleteNotification"
            :loading="deleting"
          >
            删除通知
          </el-button>
        </div>
      </el-card>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-wrapper">
        <el-skeleton :rows="8" animated />
      </div>

      <!-- 未找到通知 -->
      <el-card v-if="!loading && !notification" class="not-found-card">
        <div class="not-found">
          <el-icon class="not-found-icon" size="48"><DocumentDelete /></el-icon>
          <h3>通知不存在</h3>
          <p>该通知可能已被删除或不存在</p>
          <el-button type="primary" @click="goBack">返回通知列表</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, DocumentDelete } from '@element-plus/icons-vue'
import { useNotificationStore } from '@/stores/notification'
import api from '@/utils/api'

const route = useRoute()
const router = useRouter()
const notificationStore = useNotificationStore()

const notification = ref(null)
const loading = ref(true)
const markingAsRead = ref(false)
const deleting = ref(false)

// 获取通知详情
const fetchNotificationDetail = async () => {
  try {
    loading.value = true
    const notificationId = route.params.id
    
    const response = await api.get(`/notifications/${notificationId}`)
    notification.value = response.data
  } catch (error) {
    console.error('获取通知详情失败:', error)
    ElMessage.error('获取通知详情失败')
  } finally {
    loading.value = false
  }
}

// 标记为已读
const markAsRead = async () => {
  try {
    markingAsRead.value = true
    await api.patch(`/notifications/${notification.value.id}/read`)
    notification.value.status = 'READ'
    notification.value.readAt = new Date().toISOString()
    ElMessage.success('已标记为已读')
    
    // 更新store中的统计数据
    await notificationStore.fetchNotificationStats()
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  } finally {
    markingAsRead.value = false
  }
}

// 删除通知
const deleteNotification = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条通知吗？此操作不可撤销。',
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    deleting.value = true
    await api.delete(`/notifications/${notification.value.id}`)
    ElMessage.success('通知已删除')
    
    // 更新store中的统计数据
    await notificationStore.fetchNotificationStats()
    
    // 返回通知列表
    goBack()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除通知失败:', error)
      ElMessage.error('删除通知失败')
    }
  } finally {
    deleting.value = false
  }
}

// 返回通知列表
const goBack = () => {
  router.push('/notifications')
}

// 跳转到相关页面
const goToRelatedPage = () => {
  switch (notification.value.type) {
    case 'AVATAR_APPROVED':
    case 'AVATAR_REJECTED':
      router.push('/profile?tab=avatar')
      break
    case 'SYSTEM_NOTICE':
      // 可以跳转到系统公告页面
      break
    case 'SECURITY_ALERT':
      // 可以跳转到安全设置页面
      router.push('/profile?tab=security')
      break
    default:
      ElMessage.info('该通知类型暂无相关页面')
      break
  }
}

// 判断是否有相关页面
const hasRelatedPage = (type) => {
  return ['AVATAR_APPROVED', 'AVATAR_REJECTED', 'SECURITY_ALERT'].includes(type)
}

// 获取相关页面按钮文本
const getRelatedPageText = (type) => {
  switch (type) {
    case 'AVATAR_APPROVED':
    case 'AVATAR_REJECTED':
      return '前往头像管理'
    case 'SECURITY_ALERT':
      return '前往安全设置'
    default:
      return '查看相关页面'
  }
}

// 获取通知类型文本
const getTypeText = (type) => {
  const typeMap = {
    'AVATAR_APPROVED': '头像审核通过',
    'AVATAR_REJECTED': '头像审核拒绝',
    'SYSTEM_NOTICE': '系统通知',
    'SECURITY_ALERT': '安全警告'
  }
  return typeMap[type] || '其他通知'
}

// 获取类型标签样式
const getTypeTagType = (type) => {
  const typeMap = {
    'AVATAR_APPROVED': 'success',
    'AVATAR_REJECTED': 'danger',
    'SYSTEM_NOTICE': 'info',
    'SECURITY_ALERT': 'warning'
  }
  return typeMap[type] || 'info'
}

// 格式化内容
const formatContent = (content) => {
  if (!content) return ''
  
  // 简单的文本格式化，将换行符转换为 <br>
  return content.replace(/\n/g, '<br>')
}

// 格式化时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

onMounted(() => {
  fetchNotificationDetail()
})
</script>

<style scoped>
.notification-detail {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.back-button {
  flex-shrink: 0;
}

.page-header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.content-wrapper {
  width: 100%;
}

.notification-card {
  margin-bottom: 24px;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #EBEEF5;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.notification-title {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.status-tag {
  flex-shrink: 0;
}

.type-section {
  flex-shrink: 0;
}

.type-tag {
  font-size: 12px;
}

.notification-content {
  margin-bottom: 24px;
}

.notification-content h3 {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 16px;
  font-weight: 500;
}

.content-text {
  color: #303133;
  line-height: 1.6;
  font-size: 14px;
  padding: 16px;
  background-color: #F5F7FA;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.notification-meta {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #FAFAFA;
  border-radius: 6px;
}

.meta-item {
  display: flex;
  margin-bottom: 8px;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.meta-label {
  color: #909399;
  font-weight: 500;
  min-width: 80px;
  flex-shrink: 0;
}

.meta-value {
  color: #303133;
  font-family: monospace;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.loading-wrapper {
  padding: 24px;
}

.not-found-card {
  text-align: center;
}

.not-found {
  padding: 48px 24px;
}

.not-found-icon {
  color: #C0C4CC;
  margin-bottom: 16px;
}

.not-found h3 {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 18px;
}

.not-found p {
  margin: 0 0 24px 0;
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notification-detail {
    padding: 16px;
  }
  
  .notification-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .title-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .meta-item {
    flex-direction: column;
    gap: 4px;
  }
  
  .meta-label {
    min-width: auto;
  }
}
</style>
